from flask import Flask, request, jsonify, render_template, send_from_directory, redirect, url_for, flash
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
from werkzeug.utils import secure_filename
from werkzeug.security import check_password_hash, generate_password_hash
from PIL import Image
import os
import uuid
import json
from datetime import datetime
import shutil

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max file size

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('thumbnails', exist_ok=True)

# 登录管理器
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

# 支持的图片格式
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}

# 用户数据（实际项目中应使用数据库）
users_db = {
    'admin': {
        'password': generate_password_hash('admin123'),
        'role': 'admin'
    },
    'user': {
        'password': generate_password_hash('user123'),
        'role': 'user'
    }
}

# 图片数据库（JSON文件）
IMAGES_DB = 'images_db.json'

class User(UserMixin):
    def __init__(self, username, role):
        self.id = username
        self.username = username
        self.role = role

@login_manager.user_loader
def load_user(user_id):
    if user_id in users_db:
        return User(user_id, users_db[user_id]['role'])
    return None

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def load_images_db():
    """加载图片数据库"""
    if os.path.exists(IMAGES_DB):
        with open(IMAGES_DB, 'r', encoding='utf-8') as f:
            return json.load(f)
    return {}

def save_images_db(data):
    """保存图片数据库"""
    with open(IMAGES_DB, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def create_thumbnail(image_path, thumbnail_path, size=(200, 200)):
    """创建缩略图"""
    try:
        with Image.open(image_path) as img:
            img.thumbnail(size, Image.Resampling.LANCZOS)
            img.save(thumbnail_path, optimize=True)
        return True
    except Exception as e:
        print(f"Error creating thumbnail: {e}")
        return False

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users_db and check_password_hash(users_db[username]['password'], password):
            user = User(username, users_db[username]['role'])
            login_user(user)
            
            if user.role == 'admin':
                return redirect(url_for('admin_dashboard'))
            else:
                return redirect(url_for('user_gallery'))
        else:
            flash('用户名或密码错误')
    
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('index'))

@app.route('/admin')
@login_required
def admin_dashboard():
    if current_user.role != 'admin':
        return redirect(url_for('user_gallery'))
    return render_template('admin.html')

@app.route('/gallery')
@login_required
def user_gallery():
    return render_template('gallery.html')

@app.route('/api/upload', methods=['POST'])
@login_required
def upload_image():
    if current_user.role != 'admin':
        return jsonify({'error': '权限不足'}), 403
    
    if 'file' not in request.files:
        return jsonify({'error': '没有文件'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': '没有选择文件'}), 400
    
    if file and file.filename and allowed_file(file.filename):
        # 生成唯一文件名
        file_extension = file.filename.rsplit('.', 1)[1].lower()
        unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
        
        # 保存原图
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
        file.save(file_path)
        
        # 创建缩略图
        thumbnail_filename = f"thumb_{unique_filename}"
        thumbnail_path = os.path.join('thumbnails', thumbnail_filename)
        create_thumbnail(file_path, thumbnail_path)
        
        # 获取图片信息
        try:
            with Image.open(file_path) as img:
                width, height = img.size
        except:
            width, height = 0, 0
        
        file_size = os.path.getsize(file_path)
        
        # 保存到数据库
        images_db = load_images_db()
        image_id = unique_filename.split('.')[0]
        
        images_db[image_id] = {
            'id': image_id,
            'filename': unique_filename,
            'original_name': file.filename,
            'upload_time': datetime.now().isoformat(),
            'uploader': current_user.username,
            'width': width,
            'height': height,
            'size': file_size,
            'thumbnail': thumbnail_filename
        }
        
        save_images_db(images_db)
        
        return jsonify({
            'success': True,
            'image_id': image_id,
            'filename': unique_filename,
            'message': '上传成功'
        })
    
    return jsonify({'error': '不支持的文件格式'}), 400

@app.route('/api/images')
@login_required
def get_images():
    images_db = load_images_db()
    images_list = list(images_db.values())
    
    # 按上传时间排序
    images_list.sort(key=lambda x: x['upload_time'], reverse=True)
    
    return jsonify(images_list)

@app.route('/api/images/<image_id>', methods=['DELETE'])
@login_required
def delete_image(image_id):
    if current_user.role != 'admin':
        return jsonify({'error': '权限不足'}), 403
    
    images_db = load_images_db()
    
    if image_id not in images_db:
        return jsonify({'error': '图片不存在'}), 404
    
    image_info = images_db[image_id]
    
    # 删除原图
    image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_info['filename'])
    if os.path.exists(image_path):
        os.remove(image_path)
    
    # 删除缩略图
    thumbnail_path = os.path.join('thumbnails', image_info['thumbnail'])
    if os.path.exists(thumbnail_path):
        os.remove(thumbnail_path)
    
    # 从数据库删除
    del images_db[image_id]
    save_images_db(images_db)
    
    return jsonify({'success': True, 'message': '删除成功'})

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/thumbnails/<filename>')
def thumbnail_file(filename):
    return send_from_directory('thumbnails', filename)

@app.route('/api/stats')
@login_required
def get_stats():
    if current_user.role != 'admin':
        return jsonify({'error': '权限不足'}), 403
    
    images_db = load_images_db()
    
    total_images = len(images_db)
    total_size = sum(img['size'] for img in images_db.values())
    
    # 计算今日上传数量
    today = datetime.now().date()
    today_uploads = sum(1 for img in images_db.values() 
                       if datetime.fromisoformat(img['upload_time']).date() == today)
    
    return jsonify({
        'total_images': total_images,
        'total_size': total_size,
        'today_uploads': today_uploads,
        'total_size_mb': round(total_size / (1024 * 1024), 2)
    })

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
